
package com.lzb.compressmaster.dialog;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import com.blankj.utilcode.util.ToastUtils;
import com.lzb.compressmaster.R;
import com.lzb.compressmaster.basic.BaseSmartDialog;
import com.lzb.compressmaster.databinding.DialogSearchBinding;

public class SearchDialog extends BaseSmartDialog<DialogSearchBinding> implements View.OnClickListener {

    public SearchDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean canceledOnTouchOutside() {
        return true;
    }

    @Override
    protected int getGravity() {
        return Gravity.TOP;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_search;
    }

    @Override
    protected void initView(View view) {
        mDataBinding.tvCancel.setOnClickListener(this);
        mDataBinding.ivClear.setOnClickListener(this);

        mDataBinding.etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString();
                if (TextUtils.isEmpty(str)) {
                    mDataBinding.ivClear.setVisibility(View.INVISIBLE);
                } else {
                    mDataBinding.ivClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 设置回车键为搜索
        mDataBinding.etName.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH ||
                    (event != null && event.getKeyCode() == android.view.KeyEvent.KEYCODE_ENTER)) {

                String searchText = mDataBinding.etName.getText().toString().trim();
                if (!TextUtils.isEmpty(searchText)) {
                    dismiss();
                    if (listener != null) {
                        listener.clickSearch(searchText);
                    }
                    return true;
                } else {
                    ToastUtils.showShort(R.string.please_input_file_name);
                    return true;
                }
            }
            return false;
        });

        setupImmersiveStatusBar();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvCancel) {
            dismiss();
        } else if (id == R.id.tvConfirm) {
            if (!TextUtils.isEmpty(mDataBinding.etName.getText().toString().trim())) {
                dismiss();
                if (listener != null) {
                    listener.clickSearch(mDataBinding.etName.getText().toString());
                }
            } else {
                ToastUtils.showShort(R.string.please_input_file_name);
            }
        } else if (id == R.id.ivClear) {
            mDataBinding.etName.setText("");
        }
    }

    private Ilistener listener;

    public void setListener(Ilistener listener) {
        this.listener = listener;
    }

    public interface Ilistener {
        void clickSearch(String name);
    }

    /**
     * 设置背景变暗程度
     * @param dimAmount 变暗程度 0.0f-1.0f，0.0f为不变暗，1.0f为全黑
     */
    public void setBackgroundDim(float dimAmount) {
        Window window = getWindow();
        if (window != null) {
            if (dimAmount > 0.0f) {
                window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                WindowManager.LayoutParams params = window.getAttributes();
                params.dimAmount = Math.max(0.0f, Math.min(1.0f, dimAmount));
                window.setAttributes(params);
            } else {
                window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            }
        }
    }

    /**
     * 启用背景变暗（默认0.6f）
     */
    public void enableBackgroundDim() {
        setBackgroundDim(0.6f);
    }

    /**
     * 禁用背景变暗
     */
    public void disableBackgroundDim() {
        setBackgroundDim(0.0f);
    }

    // 修改setupImmersiveStatusBar方法，使用默认变暗
    private void setupImmersiveStatusBar() {
        Window window = getWindow();
        if (window != null) {
            // 默认启用背景变暗
            enableBackgroundDim();
            
            // 设置状态栏透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            }
            
            // 设置内容延伸到状态栏
            View decorView = window.getDecorView();
            decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            );
            
            // 设置布局参数
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.TOP;
            params.y = 0; // 紧贴状态栏
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
            window.setAttributes(params);
        }
    }

    private void setupFullScreenDialog() {
        Window window = getWindow();
        if (window != null) {
            // 设置全屏模式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                window.setNavigationBarColor(Color.TRANSPARENT);
            }

            // 设置内容全屏显示
            View decorView = window.getDecorView();
            int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                flags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }

            decorView.setSystemUiVisibility(flags);

            // 设置窗口属性
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.TOP;
            params.y = 0;
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
            window.setAttributes(params);
        }
    }
}
